package com.mesd.killer.util;

import java.security.MessageDigest;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

/**
 * String Utility Class This is used to encode passwords programmatically
 * <p/>
 * <p/>
 * <a h ref="StringUtil.java.html"><i>View Source</i></a>
 * </p>
 * 
 */
public class StringUtil
{
	// ~ Static fields/initializers
	// =============================================

	private StringUtil()
	{
	}

	// ~ Methods
	// ================================================================

	/**
	 * Generate a special length password string, which contains of 'a'-'z',
	 * 'A'-'Z', '0'-'9'
	 * 
	 * @param length
	 * @return String
	 */
	public static String randomPassword(int length)
	{
		StringBuffer password = new StringBuffer();
		int index = 0;
		while (index < length)
		{
			char ascii = (char) Math.floor(Math.random() * 125);
			if ((ascii >= 'a' && ascii <= 'z') || (ascii >= 'A' && ascii <= 'Z')
				|| (ascii >= '0' && ascii <= '9'))
			{
				password.append(String.valueOf(ascii));
				index++;
			}
		}
		return password.toString();
	}

	public static void main(String[] args)
	{
		for (int i = 0; i < 100; i++)
			System.out.println(StringUtil.randomPassword(60));
	}

	/**
	 * Encode a string using algorithm specified in web.xml and return the
	 * resulting encrypted password. If exception, the plain credentials string
	 * is returned
	 * 
	 * @param password
	 *            Password or other credentials to use in authenticating this
	 *            username
	 * @param algorithm
	 *            Algorithm used to do the digest
	 * @return encypted password based on the algorithm.
	 */
	public static String encodePassword(String password, String algorithm)
	{
		byte[] unencodedPassword = password.getBytes();

		MessageDigest md;
		try
		{
			// first create an instance, given the provider
			md = MessageDigest.getInstance(algorithm);
		}
		catch (Exception e)
		{

			return password;
		}

		md.reset();

		// call the update method one or more times
		// (useful when you don't know the size of your data, eg. stream)
		md.update(unencodedPassword);

		// now calculate the hash
		byte[] encodedPassword = md.digest();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < encodedPassword.length; i++)
		{
			if ((encodedPassword[i] & 0xff) < 0x10)
			{
				buf.append("0");
			}

			buf.append(Long.toString(
				encodedPassword[i] & 0xff, 16));
		}

		return buf.toString();
	}

	public static String deNull(String str)
	{
		return (str == null) ? "" : str;
	}

	public static boolean isNull(String str)
	{
		return "".equals(deNull(str));
	}

	public static List getListByToken(String str, String token)
	{
		if (str == null)
		{
			return new ArrayList();
		}
		StringTokenizer st = new StringTokenizer(str, token);
		List list = new ArrayList();
		while (st.hasMoreElements())
		{
			list.add(st.nextElement().toString().trim());
		}
		return list;
	}

	public static String getFirstUpperCaseVarName(String var)
	{
		if (var == null || "".equals(var))
		{
			return var;
		}
		return var.substring(
			0, 1).toUpperCase() + var.substring(
			1, var.length());
	}

	public static String getFirstLowerCaseVarName(String var)
	{
		if (var == null || "".equals(var))
		{
			return var;
		}
		return var.substring(
			0, 1).toLowerCase() + var.substring(
			1, var.length());
	}

	public static String removeZeroPrefix(String gmn)
	{
		if (gmn == null || !gmn.startsWith("0"))
		{
			return gmn;
		}
		return removeZeroPrefix(gmn.substring(1));
	}
	
	
	public static Map formatStrInMap(Map paraMap)
	{
		Map returnMap = new HashMap();
		Set<String> keys = paraMap.keySet();
        for (Iterator it = keys.iterator(); it.hasNext();) 
        {
            String key = (String) it.next();
            Object val = paraMap.get(key);
            if(val!=null)
            {
            	if(val instanceof String)
                {
                	String strVal = (String)val;
                	strVal = strVal.trim();
                	if(!StringUtil.isNull(strVal))
                		returnMap.put(key, "%"+strVal+"%");
                }
                else
                {
                	returnMap.put(key, val);
                }
            }
        }
        
		return returnMap;
	}
	
	public static String formatNumber(String numStr)
	{
		if(numStr!=null && numStr.startsWith("."))
		{
			return "0"+numStr;
		}
		
		return numStr;
	}
	
	public static long formatDolla(String strDolla)
	{
		long res = 0;
		try
		{
			if(strDolla!=null && strDolla.contains("$"))
			{
				res = Long.valueOf(strDolla.substring(strDolla.indexOf("$")+1)).longValue();
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			res = 0;
		}
		
		return res;
	}
	
	public static String formatMsg(String patter,Object[] args)
	{
		return  MessageFormat.format(
			patter, args);
	}
	
}
